﻿var curobj = [], selectedItems = [];
var sortCount = 0, whereCount = 0, joinCount = 1, groupCount = 0, havingCount = 0;
$().ready(function () {

    //  var curobj = [{ "name": "q", "data": "" }, {}];

    $("#tabs").tabs();
    //以下为模型ID列表绑定
    var mxid = request("mxid");
    itemParam = { "textField": "name", "valueField": "value" };
    ajaxParam = { "url": "../AjaxServer/BusinessModel/YwkModleParaMeterHandler.ashx", "data": { "action": "GetBusinessModelId"} }
    initDropDownList("selMxid", ajaxParam, itemParam);
    $("#selMxid").val(mxid);
    // $("#selMxid option: first").val(mxid);
    $("[name='selMxid']").attr("disabled", "disabled");
    var setting = {
        async: {
            enable: true,
            url: "../AjaxServer/BusinessModel/BusinessModelEdit.ashx",
            autoParam: ["id", "name=n", "level=lv"],
            otherParam: { "action": "GetTablesByDataSourceId", "mxid": mxid },
            dataFilter: filter
        },
        check: {
            enable: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: zTreeOnClick

        }
    };

    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        for (var i = 0, l = childNodes.length; i < l; i++) {
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
        }
        return childNodes;
    }
    $.fn.zTree.init($("#treeDemo"), setting);
    //点击选择数据源弹出选择数据源对话框
    $("#selectDataSource").on("click", function () {

        tb_show("选择表", "SelectDataTable.aspx?mxid=" + $("#selMxid").val() + "&keepThis=true&TB_iframe=true&height=420&width=600", false);
    });

    //关闭表格弹出层
    $(document).on("click", ".tbClose", function () {
        var tbname = $(this).parent().parent().attr("id");
        tbname = tbname.slice(4);
        var delobj = {};
        $($(this).parent().parent()).remove();
        for (var k = 0, len = curobj.length; k < len; k++) {
            if (curobj[k].name == tbname) {
                delobj = curobj[k];
                curobj.splice(k, 1);
                //寻找所有使用已关闭层的选项 并删除
                refreshOptions(delobj, "del");

                break;
            }
        }
    });
    //选中表项目
    $(document).on("click", ".dragTable input[type='checkbox']", function () {

        var temp, temptrid, tbname;
        //选中 顶部checkbox
        if ($(this).attr("name") == 'headerCheckbox') {
            temp = $("#tb_" + $(this).attr("id") + " input[name='childCheckbox']");
            if ($(this).is(':checked')) {
                //选中	
                for (var i = 0, len = temp.length; i < len; i++) {
                    temptrid = $($("#tb_" + $(this).attr("id") + " tr")[i + 1]).attr("id");
                    selectedItems.push(temptrid);
                    $(temp[i]).prop("checked", true);
                }

            }
            else {
                //取消选中
                for (var i = 0, len = temp.length; i < len; i++) {
                    temptrid = $($("#tb_" + $(this).attr("id") + " tr")[i + 1]).attr("id");
                    if ($.inArray(temptrid, selectedItems) != -1) {
                        selectedItems.splice($.inArray(temptrid, selectedItems), 1);
                    }
                    $(temp[i]).prop("checked", false);
                }
            }
            temp = "";
        } else if ($(this).attr("name") == 'childCheckbox') {
            temp = $(this).parent().parent().attr("id");
            if (browser.msie)
                temp = $(this).parent().parent().parent().attr("id");
            tbname = temp.split(":")[0];
            if ($(this).is(':checked')) {

                selectedItems.push(temp);
                $(this).prop("checked", true);
                temp = $("#tb_" + tbname + " input[name='childCheckbox']");

                //如果以选中所有child  将父设为checked	
                for (var i = 0, len = temp.length; i < len; i++) {
                    if (!$(temp[i]).is(':checked')) break;
                }
                if (i == temp.length) {
                    $("#tb_" + tbname + " input[name='headerCheckbox']").prop("checked", true);
                }

            }
            else {
                //设置父为unchecked
                if ($.inArray(temp, selectedItems) != -1) {
                    selectedItems.splice($.inArray(temp, selectedItems), 1);
                }
                $(this).prop("checked", false);
                if ($("#tb_" + tbname + " input[name='headerCheckbox']").is(':checked')) {
                    $("#tb_" + tbname + " input[name='headerCheckbox']").prop("checked", false);
                }
            }

        }

        $.unique(selectedItems);
    });

    //添加排序的行
    $(document).on("click", "#btnSortAdd", function () {
        var table = $(this).parent().siblings("table");
        sortCount++;
        var row = "";
        if (browser.msie) row += "<tbody>";
        var row = '<tr><td><input  type="checkbox"/></td><td><select id="selectSortField_' + sortCount + '" name="selectSortField_' + sortCount + '" type="selectfiled"></select></td><td><select id="selectSortType_' + sortCount + '" name="selectSortType_' + sortCount + '"><option value="ASC">ASC</option><option value="DESC">DESC</option></select></td> </tr>';
        if (browser.msie) row += "</tbody>";
        table.append(row);
        refreshOptions('#selectSortField_' + sortCount);
    });
    //添加where 的行
    $(document).on("click", "#btnWhereAdd", function () {
        var table = $(this).parent().siblings("table");
        whereCount++;
        var row = "";
        if (browser.msie) row += "<tbody>";
        var row = '<tr><td><input  type="checkbox"/></td><td><select id="selectWhereField_' + whereCount + '" name="selectWhereField_' + whereCount + '" type="selectfiled"></select></td><td><select id="selectWhereOperat_' + whereCount + '" name="selectWhereOperat_' + whereCount + '"></select></td><td> <input type="text" name="whereValue' + whereCount + '" /></td> <td><select  name="selectWhereAddType_' + whereCount + '"><option value="and">and</option><option value="or">or</option></select></td></tr>';


        if (browser.msie) row += "</tbody>";
        table.append(row);
        refreshOptions('#selectWhereField_' + whereCount);
        //更新操作符
        getOperatTypes("#selectWhereOperat_" + whereCount);
    });
    //添加having 的行
    $(document).on("click", "#btnHavingAdd", function () {
        var table = $(this).parent().siblings("table");
        havingCount++;
        var row = "";
        if (browser.msie) row += "<tbody>";
        var row = '<tr><td><input  type="checkbox"/></td><td><select id="selectHavingField_' + havingCount + '" name="selectHavingField_' + havingCount + '" type="selectfiled"></select></td><td><select id="selectHavingOperat_' + havingCount + '" name="selectHavingOperat_' + havingCount + '"></select></td><td> <input type="text" name="HavingValue' + havingCount + '" /></td> <td><select  name="selectHavingAddType_' + havingCount + '"><option value="and">and</option><option value="or">or</option></select></td></tr>';


        if (browser.msie) row += "</tbody>";
        table.append(row);
        refreshOptions('#selectHavingField_' + havingCount);
        //更新操作符
        getOperatTypes("#selectHavingOperat_" + havingCount);
    });

    //添加join 的行
    $(document).on("click", "#btnJoinAdd", function () {
        var table = $(this).parent().siblings("table");
        joinCount++;
        var row = "";
        if (browser.msie) row += "<tbody>";
        var row = '<tr><td><input  type="checkbox"/></td><td><select  name="selecJoinType_0"><option value="inner join">inner join</option><option value="left join">left join</option> <option value="right join">left join</option><option value="outter join">outter join</option></select></td><td><select id="selectjoinField_' + joinCount + '" name="selectjoinField_' + joinCount + '" type="selectfiled"></select></td><td><select id="selectjoinField_' + (joinCount + 1) + '" name="selectjoinField_' + (joinCount + 1) + '" type="selectfiled"></select></td></tr>';
        if (browser.msie) row += "</tbody>";
        table.append(row);
        refreshOptions('#selectjoinField_' + joinCount);
        refreshOptions('#selectjoinField_' + (joinCount + 1));
        joinCount++;


    });
    //添加group 的行
    $(document).on("click", "#btnGroupAdd", function () {
        var table = $(this).parent().siblings("table");
        groupCount++;
        var row = "";
        if (browser.msie) row += "<tbody>";
        var row = '<tr><td><input  type="checkbox"/></td><td><select id="selectGroupField_' + groupCount + '" name="selectGroupField_' + groupCount + '" type="selectfiled"></select></td></tr>';
        if (browser.msie) row += "</tbody>";
        table.append(row);
        refreshOptions('#selectGroupField_' + groupCount);
    });



    //删除hang
    $(document).on("click", ".btnDel", function () {
        var table = $(this).parent().siblings("table");
        var delrows = [];
        //遍历整个table 找出check的行 删除
        for (var i = 0, len = $("input[type='checkbox']", table).length; i < len; i++) {
            if ($("input[type='checkbox']", table)[i].checked) {
                delrows.push($("tr", table)[i + 1]);
            }
        }
        delArrObj(delrows);

    });

});

$(document).on("click", "#btnSubmit", function (e) {

    var jsonstr = [];
    var table = $("#tabSort");
    jsonstr += '{"SortCoulmns":['; //存储行
    var sortType = '"SortType":[' //存储行类型 
    for (var i = 1, len = $("tr", table).length; i < len; i++) {
        jsonstr += '"' + $($("select", $("tr", table)[i])[0]).val() + '",';
        sortType += '"' + $($("select", $("tr", table)[i])[1]).val() + '",';
    }
    jsonstr = jsonstr.slice(0, jsonstr.length - 1);
    sortType = sortType.slice(0, sortType.length - 1);
    jsonstr += ' ],';
    sortType += ' ],';
    jsonstr += sortType;
    table = $("#tabWhere");
    jsonstr += ' "WhereColumns":[';
    var wherePoerat = '"WherePoerat":[';
    var whereValue = '"WhereValue":[';
    var whereType = '"WhereType":[';
    for (i = 1, len = $("tr", table).length; i < len; i++) {
        jsonstr += '"' + $($("select", $("tr", table)[i])[0]).val() + '",';
        wherePoerat += '"' + $($("select", $("tr", table)[i])[1]).val() + '",';
        whereValue += '"' + $("input[type='text']", $("tr", table)[i]).val() + '",';
        whereType += '"' + $($("select", $("tr", table)[i])[2]).val() + '",';
    }
    jsonstr = jsonstr.slice(0, jsonstr.length - 1);
    wherePoerat = wherePoerat.slice(0, wherePoerat.length - 1);
    whereValue = whereValue.slice(0, whereValue.length - 1);
    whereType = whereType.slice(0, whereType.length - 1);
    jsonstr += '],';
    wherePoerat += '],';
    whereValue += '],';
    whereType += '],';
    jsonstr += wherePoerat + whereValue + whereType;
    table = $("#tabJoin");
    jsonstr += ' "JoinColumn1":[';
    var joinColumn2 = '"JoinColumn2":[';
    var joinType = '"JoinType":[';
    for (i = 1, len = $("tr", table).length; i < len; i++) {
        joinType += '"' + $($("select", $("tr", table)[i])[0]).val() + '",';
        jsonstr += '"' + $($("select", $("tr", table)[i])[1]).val() + '",';
        joinColumn2 += '"' + $($("select", $("tr", table)[i])[2]).val() + '",';
    }
    jsonstr = jsonstr.slice(0, jsonstr.length - 1);
    joinColumn2 = joinColumn2.slice(0, joinColumn2.length - 1);
    joinType = joinType.slice(0, joinType.length - 1);
    jsonstr += '],';
    joinColumn2 += '],';
    joinType += '],';
    jsonstr += joinColumn2 + joinType;

    table = $("#tabGroup");
    jsonstr += '"GroupColumns":[';
    for (i = 1, len = $("tr", table).length; i < len; i++) {
        jsonstr += '"' + $($("select", $("tr", table)[i])[0]).val() + '",';
    }
    jsonstr = jsonstr.slice(0, jsonstr.length - 1);
    jsonstr += ' ],';


    table = $("#tabHaving");
    jsonstr += '"HavingColumns":[';
    var havingOperat = '"HavingOperat":[';
    var havingValue = '"HavingValue":[';
    var havingType = '"HavingType":[';
    for (i = 1, len = $("tr", table).length; i < len; i++) {
        jsonstr += '"' + $($("select", $("tr", table)[i])[0]).val() + '",';
        havingOperat += '"' + $($("select", $("tr", table)[i])[1]).val() + '",';
        havingValue += '"' + $("input[type='text']", $("tr", table)[i]).val() + '",';
        havingType += '"' + $($("select", $("tr", table)[i])[2]).val() + '",';
    }
    jsonstr = jsonstr.slice(0, jsonstr.length - 1);
    havingOperat = havingOperat.slice(0, havingOperat.length - 1);
    havingValue = havingValue.slice(0, havingValue.length - 1);
    havingType = havingType.slice(0, havingType.length - 1);
    jsonstr += '],';
    havingOperat += '],';
    havingValue += '],';
    havingType += '],';
    jsonstr += havingOperat + havingValue + havingType;

    /*选中的列s*/
    jsonstr += '"SelectedItems":[';
    if (selectedItems.length == 0) {
        alert("至少选中一个列");
    } else {
        for (i = 0, len = selectedItems.length; i < len; i++) {
            jsonstr += '"' + selectedItems[i] + '",';
        }
    }
    jsonstr = jsonstr.slice(0, jsonstr.length - 1);
    jsonstr += ' ]}';
    //阻止冒泡事件和默认事件
    if (window.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
    else {
        e.cancelBubble = true;
        e.returnValue = true;
    }
    //$(".header").html(jsonstr);
    $.ajax({
        type: "post",
        dataType: "json",
        url: "../AjaxServer/BusinessModel/BusinessModelEdit.ashx",
        data: "action=ReciveSaveAsData&mxid=" + request("mxid") + "&json=" + jsonstr,
        success: function (message) {
//            var showFelid = ["LMC", "LX", "LDM"];
//            getContent(message, treeNode.name, showFelid);
            window.parent.tb_remove();
        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});


/*树节点点击事件，ajax远程获取表格内容*/
function zTreeOnClick(e, treeId, treeNode) {
    if (treeNode.id) {

        if ($("#tbd_" + treeNode.name).length > 0) return;
        $.ajax({
            type: "post",
            dataType: "json",
            url: "../AjaxServer/BusinessModel/YwkModleColumnHandler.ashx",
            data: "action=04&pageSize=15&pageIndex=1&mxid=" + $("#selMxid").val() + "&entityid=" + treeNode.id,
            success: function (message) {
                var showFelid = ["LMC", "LX", "LDM"];
                getContent(message, treeNode.name, showFelid);
                return false;
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });


    }
}

function getContent(obj, tname, showFelid) {

    var total = obj.totalCount;
    var data = obj.data;
    var columnInfo = obj.Header;

    var showFelidIndex = [];

    $("<div>", {
        "id": "tbd_" + tname,
        "html": "<div class='barTitle'>" + tname + "<span class='tbClose'>×</span></div>",
        "class": "dragWarp"
    }).appendTo($("#dragContent"));

    var tbHtml = "<div class='undragArea'><table class='dragTable' id='tb_" + tname + "'></table></div>";
    $(tbHtml).appendTo($("#tbd_" + tname));

    //初始化表头部分

    var header = "";
    header = "<tr ><td  > <input id=" + tname + " type=\"checkbox\" class='toptd' name=\"headerCheckbox\" value=\"checkbox\" /></td>";
    if (browser.msie)
        header = "<tbody><tr ><td width=\"50px\" > <input id=" + tname + " type=\"checkbox\" class='toptd' name=\"headerCheckbox\" value=\"checkbox\" /></td>";

    header += '<td width="60px">列代码</td><td width="60px">列名称</td><td width="180px">列类型(普通列N,计算列C)</td></tr>';

    if (browser.msie)
        header += "</body>";
    $("#tb_" + tname).append(header);

    if (total == null || data == null) {
        alert("没有符合条件的数据！！！");
        return;
    }
    $.each(data, function (a, n) {

        var row = row = "<tr onSelectStart=\"return false\"  ><td ><input type=\"checkbox\" name=\"childCheckbox\" value=\"checkbox\" /></td>";
        var col = "";
        var trId = "";

        if (browser.msie)//IE浏览器需要加上tbody标签，方能动态添加
            row = "<tbody><tr onSelectStart=\"return false\" ><td ><input type=\"checkbox\" name=\"childCheckbox\" value=\"checkbox\" /></td>";

        for (var i = 0, len = showFelid.length; i < len; i++) {
            row += "<td >";
            if (n[showFelid[i]] == null)
                row += "</td>";
            else
                row += n[showFelid[i]] + "</td>";

        }
        row += "</tr>";
        if (browser.msie)
            row += "</tbody>";
        row = $(row);

        for (var key in n) {
            trId = tname + ":" + n[key];
            break;
        }
        row.attr("id", trId);

        $("#tb_" + tname).append(row);
    });

    $("#tbd_" + tname).draggable({ cancel: ".undragArea", containment: "#dragContent" });

    curobj.push({ "name": tname, "data": data });
    refreshOptions({ "name": tname, "data": data });

}

/*每次添加或删除的时候 修改调用 可选择的列*/
function getOptions(selector) {
    var opts = "";
    /*更新所有*/
    if (selector == "" || selector == undefined) {
        for (var k = 0, len = curobj.length; k < len; k++) {
            for (var j = 0, lens = curobj[k].data.length; j < lens; j++) {
                opts += ' <option tb=' + curobj[k].name + ' value="' + curobj[k].name + ":" + curobj[k].data[j]["LDM"] + '">' + curobj[k].name + ":" + curobj[k].data[j]["LDM"] + '</option>';
            }
        }
    }
    else {
        //只更新select
        for (var j = 0, lens = selector.data.length; j < lens; j++) {
            opts += ' <option tb=' + selector.name + ' value="' + selector.name + ":" + selector.data[j]["LDM"] + '">' + selector.name + ":" + selector.data[j]["LDM"] + '</option>';
        }
    }
    return opts;
}

function refreshOptions(selector, type) {
    //更新所有
    if (selector == "" || selector == undefined) {
        $("select[type='selectfiled']").html("");
        $("select[type='selectfiled']").append(getOptions());
    }
    else if (jQuery.isPlainObject(selector) && type == undefined) {
        //对象的话 且type无值 追加入
        $("select[type='selectfiled']").append(getOptions(selector));
    }
    else if (type == "del") {
        //typy =del  删除某对象
        var sel = $("select[type='selectfiled']");
        var curselect = "", delselect = [];
        for (var i = 0, len = sel.length; i < len; i++) {
            curselect = $(sel[i]).val();
            //如若是当前选中项所属关闭表格 则删除行
            if (selector.name == curselect.split(":")[0]) {
                delselect.push($(sel[i]).parent().parent('tr'));
            }
        }
        delArrObj(delselect);
        $("option[tb='" + selector.name + "']").remove();

    }
    else {
        //更新某selector
        $(selector).html("");
        $(selector).append(getOptions());
    }

}
//删除某包含对象的数组
function delArrObj(arr) {
    for (var i = 0, len = arr.length; i < len; i++) {
        arr[i].remove();
    }
}
//获取所有操作类型   ==where中使用一次
function getOperatTypes(selector) {
    var opts = '<option value="=">=</option> <option value=">">></option> <option value="<"><</option><option value="not in">not in</option>';
    $(selector).append(opts);
}



